package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.central.Central;
import com.serverSite.Processing;

/**
 * Servlet implementation class ServAjax
 */
@WebServlet("/ServAjax")
public class ServAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
	JSONObject jSon = new JSONObject();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServAjax() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ getting and shapping parameters
		String serverLoc = request.getParameter("loc");
		int serverLocI = Integer.parseInt(serverLoc);
		String qty = request.getParameter("qty");
		int qtyI = Integer.parseInt(qty);
		String prodId = request.getParameter("productId");
		int prodIdI =  Integer.parseInt(prodId);
		//String booked = request.getParameter("bJ");
		//JSONArray jsonBooked = new JSONArray();
		//try {
		//	jsonBooked = new JSONArray(booked);
		//} catch (JSONException e2) {
		//	e2.printStackTrace();
		//}
		
		//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ creating a Central object then call the delay function
		JSONObject jsonCentral=new JSONObject();
		Central central = new Central();
		//if (!booked.isEmpty()){
		//	try {
		//		Processing  p = new Processing();//new precess object
		//		p.cancelProcess(jsonBooked, prodIdI);//for decrease the previous booked qty 
		//		jsonCentral = central.delay(serverLocI, prodIdI, qtyI, 10);//ask for delay and disponibilities
			//} catch (JSONException e) {
				//e.printStackTrace();
			//}
	//	}else{
			try {
				jsonCentral = central.delay(serverLocI, prodIdI, qtyI, 10);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		//}
		request.setAttribute("json", jsonCentral);
		PrintWriter out=response.getWriter();// tester si utile dans le fonctionnement general
		
		out.println(jsonCentral);// send the json in the jsp
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
